<template>
  <div class="wrapper" ref="wrapper">
    <div>
      <h2 class="title">热门城市</h2>
      <ul class="hot-city-list clearfix">
        <li class="city-button border"
          v-for="item in hotCities"
          :key="item.id"
          @click="handleCityClick(item.name)">
          {{ item.name }}
        </li>
      </ul>
      <h2 class="title">字母排序</h2>
      <ul v-for="(value, key) in cities"
        :key="key">
        <li class="letter-title" :ref="key">{{ key }}</li>
        <li class="city-item border-bottom"
          v-for="item in value"
          :key="item.id"
          @click="handleCityClick(item.name)">
          {{ item.name }}
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import BScroll from 'better-scroll'
import { mapState, mapMutations } from 'vuex'
import MutationTypes from '@/store/MutationTypes'
export default {
  name: 'CityList',
  props: {
    hotCities: Array,
    cities: Object
  },
  computed: mapState([
    'city', 'letter'
  ]),
  watch: {
    letter (newValue) {
      const el = this.$refs[newValue][0]
      this.scroll.scrollToElement(el)
    }
  },
  methods: {
    handleCityClick (city) {
      // 传入一个载荷
      // 载荷应该是一个对象，这样可以包含多个字段并且记录的 mutation 会更易读
      this.changeCity({
        city: city
      })
      this.$router.push('/')
    },
    ...mapMutations({
      changeCity: MutationTypes.CHANGE_CITY
    })
  },
  mounted () {
    this.scroll = new BScroll(this.$refs.wrapper, {
      click: true
    })
  }
}
</script>

<style lang="stylus" scoped>
  .wrapper
    position absolute
    top .88rem
    bottom 0
    left 0
    right 0
    overflow hidden
    background #f5f5f5
    padding-right .6rem
    .clearfix:after
      content ''
      display table
      clear both
    .title
      font-size .24rem
      padding .24rem
    .hot-city-list
      .city-button
        float left
        width 33.33%
        height .9rem
        line-height .9rem
        font-size .28rem
        background #fff
        text-align center
    .letter-title
      padding .24rem
    .city-item
      padding .24rem
      background #fff
</style>
